package com.dy.树.岛屿的个数;

/*
给定一个由 '1'（陆地）和 '0'（水）组成的的二维网格，计算岛屿的数量。一个岛被水包围，
并且它是通过水平方向或垂直方向上相邻的陆地连接而成的。你可以假设网格的四个边均被水包围。

示例 1:

输入:
11110
11010
11000
00000

输出: 1
示例 2:

输入:
11000
11000
00100
00011

输出: 3
 */
public class Solution {
    //dfs
    public int numIslands(char[][] grid) {
        if (grid.length == 0) {
            return 0;
        }
        int res = 0;
        boolean[][] visited = new boolean[grid.length][grid[0].length];
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if (!visited[i][j] && grid[i][j] == '1') {
                    numIslandsDFS(grid, visited, i, j);
                    res++;
                }
            }
        }
        return res;
    }

    private void numIslandsDFS(char[][] grid, boolean[][] visited, int x, int y) {
        if (x < 0 || x >= grid.length) return;
        if (y < 0 || y >= grid[0].length) return;
        if (grid[x][y] != '1' || visited[x][y]) return;
        visited[x][y] = true;
        numIslandsDFS(grid, visited, x + 1, y);
        numIslandsDFS(grid, visited, x - 1, y);
        numIslandsDFS(grid, visited, x, y + 1);
        numIslandsDFS(grid, visited, x, y - 1);

    }
}
